package com.kx.smsplantform.job;

import com.kx.smsplantform.email.EmailUtils;
import com.kx.smsplatform.common.constants.RabbitMQConstants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 监控RabbitMq中的消息，到达一定数量给运维发送邮件
 *
 * @Author Sun
 * @Date 2021/7/7 18:54
 */
@Slf4j
@Component
public class MonitorRabbitJob implements SimpleJob {
    @Autowired
    private ConnectionFactory factory;

    @Autowired
    private EmailUtils emailUtils;

    @Override
    public void execute(ShardingContext shardingContext) {
        // 监听MQ中的队列
        // Producer - Connection - Channel(创建队列,创建交换机,发送消息)
        Connection connection = factory.createConnection();
        Channel channel = connection.createChannel(false);

        // 声明队列名称
        String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + 1;

        // 创建队列(如果队列存在， 不用管)
        try {
            channel.queueDeclare(queueName, true, false, false, null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取队列中的消息数量
        int messageCount = 0;
        try {
            messageCount = channel.queueDeclarePassive(queueName).getMessageCount();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 判断消息数量
        if (messageCount > 10) {
            log.info("【监控模块 监听消息队列】 {}队列中的消息，出现了消息堆积，消息的数量为：{}", queueName, messageCount);
            //发送信息给运维人员
            emailUtils.sendSimpleMail("173108266@qq.com", "RabbitMQ消息堆积", queueName + "队列中的消息，出现了消息堆积，消息的数量为" + messageCount);
        } else {
            log.info("【监控模块 监听消息队列】 {}队列中的消息，没有出现堆积问题！", queueName);
        }
    }
}
